﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using NHibernate;
using NHibernate.Context;
using NHibernate.Cfg;

namespace NhConfig
{
    public class ExampleDataCreate
    {
        private readonly ISessionFactory _sessionFactory;

        public ExampleDataCreate(ISessionFactory sessionFactory)
        {
            if (sessionFactory == null)
                throw new ArgumentNullException("SessionFactory");
            _sessionFactory = sessionFactory;
        }

        private static void ClearDataBase(ISession session)
        {
            session.CreateQuery("delete from ActorRole").ExecuteUpdate();
            session.CreateQuery("delete from Product").ExecuteUpdate();
        }

        private static void CreateMovies(ISession session)
        {
            session.Save(new Eg.Core.Movie()
            {
                Description = "Awesome",
                Name = "Raidern of the lost ark.",
                Director = "Steven",
                UnitPrice = 122m,
                Actors = new List<Eg.Core.ActorRole>(){
                new Eg.Core.ActorRole(){ Role = "Indain", Actor = "Mecekyz"}
              }
            });

            session.Save(new Eg.Core.Movie()
            {
                Description = "The bucket list",
                Name = "Good movie",
                Director = "Jack",
                UnitPrice = 234m,
                Actors = new List<Eg.Core.ActorRole>() { 
                  new Eg.Core.ActorRole(){
                   Actor = "Bob", Role = "binly"
                  },
                  new Eg.Core.ActorRole(){
                   Actor = "Bob2", Role = "binlyz"
                  }
            }
            });
        }

        private static void CreateBooks(ISession session)
        {
            session.Save(new Eg.Core.Book() { Author = "Jason", Description = "Nhibernate example", ISBN = "978-123-45", Name = "Nhibernate cokbook", UnitPrice = 123m });
        }

        public void SetupDataBase()
        {
            using(var session = _sessionFactory.OpenSession())
            using (var trans = session.BeginTransaction())
            {
                ClearDataBase(session);
                CreateMovies(session);
                CreateBooks(session);
                trans.Commit();
            }

        }
    }
}
